<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix header">
        <span>新增 API</span>
      </div>
      <el-form :model="newApi" :rules="rules" ref="newApiForm" label-width="120px" class="demo-newApiForm">
        <el-form-item label="API 名字" prop="name">
          <el-input v-model="newApi.name" placeholder="请输入 API 名字" clearable></el-input>
        </el-form-item>
        <el-form-item label="测试链接" prop="testLink">
          <el-input v-model="newApi.testLink" placeholder="请输入测试链接" clearable></el-input>
        </el-form-item>
        <el-form-item label="API URL" prop="apiUrl">
          <el-input v-model="newApi.apiUrl" placeholder="请输入 API URL" clearable></el-input>
        </el-form-item>
        <el-form-item label="接口提供方" prop="provider">
          <el-input v-model="newApi.provider" placeholder="请输入接口提供方" clearable></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="newApi.description" placeholder="请输入描述" clearable></el-input>
        </el-form-item>
        <el-form-item label="API 种类" prop="type">
          <el-select v-model="newApi.type" placeholder="请选择">
            <el-option v-for="item in apiTypes" :key="item.id" :label="item.categoryName" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select v-model="newApi.tags" placeholder="请选择标签" multiple>
            <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可见范围" prop="visibility">
          <el-select v-model="newApi.visibility" placeholder="请选择可见范围">
            <el-option v-for="option in visibilityOptions" :key="option" :label="option" :value="option"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版权信息" prop="copyright">
          <el-input v-model="newApi.copyright" placeholder="请输入版权信息" clearable></el-input>
        </el-form-item>
        <el-form-item label="相关文章">
          <el-input v-model="newApi.relatedArticles" placeholder="请输入相关文章（以逗号分隔）" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否需要 Token" prop="needToken">
          <el-switch v-model="newApi.needToken" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('newApiForm')">立即创建</el-button>
          <el-button @click="resetForm('newApiForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      newApi: {
        name: '',
        testLink: '',
        apiUrl: '',
        provider: '',
        updateTime: '',
        description: '',
        type: '',
        tags: [],
        visibility: '',
        copyright: '',
        relatedArticles: '',
        needToken: false
      },
      apiTypes: [],
      tags: [], // 标签列表
      visibilityOptions: ['公开', '私有'], // 可见范围选项
      rules: {
        name: [
          { required: true, message: '请输入API名字', trigger: 'blur' }
        ],
        testLink: [
          { required: true, message: '请输入测试链接', trigger: 'blur' }
        ],
        apiUrl: [
          { required: true, message: '请输入API URL', trigger: 'blur' }
        ],
        provider: [
          { required: true, message: '请输入接口提供方', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择API种类', trigger: 'change' }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: 'change' }
        ],
        visibility: [
          { required: true, message: '请选择可见范围', trigger: 'change' }
        ],
        copyright: [
          { required: true, message: '请输入版权信息', trigger: 'blur' }
        ],
        relatedArticles: [
          { required: false, message: '请输入相关文章', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchApiTypes();
    this.fetchTags();
  },
  methods: {
    fetchApiTypes() {
      axios.get('/api/system/catelog')
        .then(response => {
          this.apiTypes = response.data.apiKinds;
        })
        .catch(error => {
          console.error('获取API种类失败', error);
        });
    },
    fetchTags() {
      axios.get('/api/system/tags')
        .then(response => {
          this.tags = response.data.tags; // 假设接口返回的格式
        })
        .catch(error => {
          console.error('获取标签失败', error);
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formattedData = {
            name: this.newApi.name,
            testLink: this.newApi.testLink,
            apiUrl: this.newApi.apiUrl,
            provider: this.newApi.provider,
            description: this.newApi.description,
            type: this.newApi.type.id,
            tags: this.newApi.tags,
            visibility: this.newApi.visibility,
            copyright: this.newApi.copyright,
            relatedArticles: this.newApi.relatedArticles.split(','), // 处理相关文章为数组
            needToken: this.newApi.needToken
          };
  
          axios.post('/api/system/apiAdd', formattedData)
            .then(response => {
              this.$message({
                message: 'API创建成功',
                type: 'success'
              });
              this.resetForm(formName); // 重置表单
            })
            .catch(error => {
              this.$message({
                message: 'API创建失败，请重试',
                type: 'error'
              });
              console.error(error);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style scoped>
.box-card {
  width: 600px;
  margin: 20px auto;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.header {
  background-color: #f0f4f8;
  font-weight: bold;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
}

.demo-newApiForm {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
}

.el-input,
.el-select {
  border-radius: 4px;
}

.el-button {
  border-radius: 4px;
}
</style>
